<template>
    <div class="app-container">
        <FilterSearch v-show="showSearch" class="filter-search" :value="queryParams" :config="configData">
        </FilterSearch>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        <el-table v-if="refreshTable" v-loading="loading" :data="dataList" row-key="menuId"
            :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
            <el-table-column type="index" label="序号" minWidth="60">
                <template #default="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column prop="menuName" label="菜单名称" :show-overflow-tooltip="true"
                minWidth="160"></el-table-column>
            <el-table-column prop="icon" label="图标" align="center" minWidth="120">
                <template #default="scope">
                    <svg-icon :icon-class="scope.row.icon" />
                </template>
            </el-table-column>
            <el-table-column prop="menuType" label="菜单类型" sortable minWidth="120">
                <template #default="scope">
                    <el-tag type="success" v-if="scope.row.menuType == 'M'">目录</el-tag>
                    <el-tag v-else-if="scope.row.menuType == 'C'">菜单</el-tag>
                    <el-tag type="warning" v-else>按钮</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="menuSort" label="排序" sortable minWidth="80"></el-table-column>
            <el-table-column prop="name" label="权限标识" :show-overflow-tooltip="true" minWidth="120"></el-table-column>
            <el-table-column prop="path" label="路由地址" :show-overflow-tooltip="true" minWidth="180"></el-table-column>
            <el-table-column prop="component" label="组件路径" :show-overflow-tooltip="true"
                minWidth="160"></el-table-column>
            <el-table-column prop="status" label="状态" minWidth="80">
                <template #default="scope">
                    <dict-tag :options="statusOptions" :value="scope.row.status"></dict-tag>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="显示状态" minWidth="80">
                <template #default="scope">
                    <dict-tag :options="hiddenOptions" :value="scope.row.hidden"></dict-tag>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="是否嵌套显示" minWidth="120">
                <template #default="scope">
                    <dict-tag :options="whetherOptions" :value="scope.row.alwaysShow"></dict-tag>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="是否缓存" minWidth="80">
                <template #default="scope">
                    <dict-tag :options="noCacheOptions" :value="scope.row.noCache"></dict-tag>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="导航栏" minWidth="80">
                <template #default="scope">
                    <dict-tag :options="hiddenOptions" :value="scope.row.breadcrumb"></dict-tag>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="导航栏操作" minWidth="120">
                <template #default="scope">
                    <el-tag type="success" v-if="scope.row.affix == 1">删除</el-tag>
                    <el-tag type="info" v-else>禁止删除</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="isFrame" label="是否外链" minWidth="80">
                <template #default="scope">
                    <dict-tag :options="whetherOptions" :value="scope.row.isFrame"></dict-tag>
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" minWidth="200" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="创建时间" align="center" sortable minWidth="180" prop="createTime">
            </el-table-column>
            <el-table-column label="更新时间" align="center" sortable minWidth="180" prop="updateTime">
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" minWidth="210"
                class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button v-hasPermi="['system:menu:edit']" link type="primary" icon="Edit"
                        @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button v-hasPermi="['system:menu:add']" link type="primary" icon="Plus"
                        @click="handleAdd(scope.row)">新增</el-button>
                    <el-button v-hasPermi="['system:menu:remove']" link type="primary" icon="Delete"
                        @click="handleRemove(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加或编辑菜单对话框 -->
        <el-dialog v-model="open" :title="title" width="880px" append-to-body>
            <el-form ref="menuRef" :model="form" :rules="rules" label-width="130px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="上级菜单">
                            <el-tree-select v-model="form.parentId" :data="menuOptions"
                                :props="{ value: 'menuId', label: 'menuName', children: 'children' }" value-key="menuId"
                                placeholder="选择上级菜单" class="el-tree-select" :disabled="form.menuType == 'M'" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="菜单名称" prop="menuName">
                            <el-input v-model="form.menuName" clearable placeholder="请输入菜单名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="菜单类型" prop="menuType">
                            <el-radio-group v-model="form.menuType" :disabled="title == '编辑'" @change="handleRadio">
                                <el-radio label="M">目录</el-radio>
                                <el-radio label="C">菜单</el-radio>
                                <el-radio label="F">按钮</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col v-if="form.menuType != 'F'" :span="12">
                        <el-form-item label="菜单图标" prop="icon">
                            <el-popover v-model:hidden="showChooseIcon" placement="bottom-start" :width="540"
                                trigger="click" @show="showSelectIcon">
                                <template #reference>
                                    <el-input v-model="form.icon" v-click-outside="hideSelectIcon" placeholder="点击选择图标"
                                        readonly @blur="showSelectIcon">
                                        <template #prefix>
                                            <svg-icon v-if="form.icon" :icon-class="form.icon" class="el-input__icon"
                                                style="height: 32px; width: 16px" />
                                            <el-icon v-else style="height: 32px; width: 16px">
                                                <search />
                                            </el-icon>
                                        </template>
                                    </el-input>
                                </template>
                                <IconSelect ref="iconSelectRef" @selected="selected" />
                            </el-popover>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="高亮显示">
                            <template #label>
                                <span>
                                    <el-tooltip content="当本菜单左侧隐藏时,进入页面之后左侧选定菜单高亮(/system/menu)" placement="top">
                                        <el-icon><question-filled /></el-icon>
                                    </el-tooltip>
                                    高亮显示
                                </span>
                            </template>
                            <el-input v-model="form.activeMenu" clearable placeholder="请输入高亮显示菜单路径" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="路由地址" prop="path">
                            <template #label>
                                <span>
                                    <el-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头" placement="top">
                                        <el-icon><question-filled /></el-icon>
                                    </el-tooltip>
                                    路由地址
                                </span>
                            </template>
                            <el-input v-model="form.path" clearable placeholder="请输入路由地址,父组件需要加/前缀,子组件不能加/前缀" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="组件路径">
                            <el-input v-model="form.component" clearable :disabled="form.menuType == 'D'"
                                placeholder="请输入组件路径,例如(system/menu),如果是目录一律写为(Layout)" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="权限标识">
                            <el-input v-model="form.name" clearable placeholder="请输入权限标识" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="重定向">
                            <el-input v-model="form.redirect" clearable placeholder="请输入重定向标识" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="显示排序">
                            <el-input-number v-model="form.menuSort" controls-position="right" :min="0" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="">
                            <template #label>
                                <span>
                                    <el-tooltip content="选择是外链则路由地址需要以`http(s)://`开头" placement="top">
                                        <el-icon><question-filled /></el-icon> </el-tooltip>是否外链
                                </span>
                            </template>
                            <el-radio-group v-model="form.isFrame">
                                <el-radio :label="item.value" v-for="(item, index) in whetherOptions" :key="index">{{
                                    item.label
                                    }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="">
                            <template #label>
                                <span>
                                    <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                                        <el-icon><question-filled /></el-icon>
                                    </el-tooltip>
                                    状态
                                </span>
                            </template>
                            <el-radio-group v-model="form.status">
                                <el-radio :label="item.value" v-for="(item, index) in statusOptions" :key="index">{{
                                    item.label
                                    }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="">
                            <template #label>
                                <span>
                                    <el-tooltip content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问" placement="top">
                                        <el-icon><question-filled /></el-icon>
                                    </el-tooltip>
                                    显示状态
                                </span>
                            </template>
                            <el-radio-group v-model="form.hidden">
                                <el-radio :label="item.value" v-for="(item, index) in hiddenOptions" :key="index">{{
                                    item.label
                                    }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="">
                            <template #label>
                                <span>
                                    <el-tooltip content="是否显示下级" placement="top">
                                        <el-icon><question-filled /></el-icon>
                                    </el-tooltip>
                                    显示下级
                                </span>
                            </template>
                            <el-radio-group v-model="form.alwaysShow">
                                <el-radio :label="item.value" v-for="(item, index) in whetherOptions" :key="index">{{
                                    item.label
                                    }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="">
                            <template #label>
                                <span>
                                    <el-tooltip content="是否缓存页面组件" placement="top">
                                        <el-icon><question-filled /></el-icon>
                                    </el-tooltip>
                                    缓存页面组件
                                </span>
                            </template>
                            <el-radio-group v-model="form.noCache">
                                <el-radio :label="item.value" v-for="(item, index) in noCacheOptions" :key="index">{{
                                    item.label
                                    }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="">
                            <template #label>
                                <span>
                                    <el-tooltip content="导航栏是否记录" placement="top">
                                        <el-icon><question-filled /></el-icon>
                                    </el-tooltip>
                                    导航栏记录
                                </span>
                            </template>
                            <el-radio-group v-model="form.breadcrumb">
                                <el-radio :label="item.value" v-for="(item, index) in hiddenOptions" :key="index">{{
                                    item.label
                                    }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="">
                            <template #label>
                                <span>
                                    <el-tooltip content="是否在导航栏可删除" placement="top">
                                        <el-icon><question-filled /></el-icon>
                                    </el-tooltip>
                                    导航栏可删除
                                </span>
                            </template>
                            <el-radio-group v-model="form.affix">
                                <el-radio :label="item.value" v-for="(item, index) in whetherOptions" :key="index">{{
                                    item.label
                                    }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input v-model="form.remark" rows="3" resize="none" type="textarea"
                                placeholder="请输入内容"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Menu" lang="ts">
/* eslint-disable camelcase */
import { menuList, menuAdd, menuEdit, menuRemove } from '@/api/system/menu';
import SvgIcon from '@/components/SvgIcon/index.vue';
import IconSelect from '@/components/IconSelect/index.vue';
import { ClickOutside as vClickOutside } from 'element-plus';
import { getCurrentInstance, ComponentInternalInstance, ref, reactive, toRefs, nextTick, computed } from 'vue';
import { statusOptions, whetherOptions, noCacheOptions, hiddenOptions } from '@/constant';

interface MenuItem {
    id?: number | null;
    menuId?: number | null;
    parentId?: number | null;
    menuName?: string | null;
    icon?: string | null;
    path?: string | null;
    component?: string | null;
    menuSort?: number | null;
    redirect?: string | null;
    status?: number | null;
    hidden?: number | null;
    noCache?: number | null;
    alwaysShow?: number | null;
    breadcrumb?: number | null;
    affix?: number | null;
    menuType?: string | null;
    isFrame?: number | null;
    name?: string | null;
    remark?: string | null;
    [key: string]: any;
}


const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const dataList = ref<any[]>([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref('');
const menuOptions = ref<any[]>([]);
const isExpandAll = ref(false);
const refreshTable = ref(true);
const showChooseIcon = ref(false);
const iconSelectRef = ref<any>(null);

const data = reactive<{
    form: MenuItem;
    queryParams: any;
    rules: any;
}>({
    form: {
      menuId: null,
      parentId: null,
      menuName: "",
      icon: "",
      path: "",
      component: "Layout",
      menuSort: 0,
      redirect: "",
      status: 1,
      hidden: 1,
      noCache: 2,
      alwaysShow: 2,
      breadcrumb: 1,
      affix: 1,
      menuType: "D",
      isFrame: 2,
      name: "",
      remark: ""
    } as MenuItem,
    queryParams: {
        menuName: undefined,
        status: undefined,
        createTime: undefined
    },
    rules: {
        menuName: [{ required: true, message: '菜单名称不能为空', trigger: ['blur', 'change']}],
        path: [{ required: true, message: '路由地址不能为空', trigger: ['blur', 'change']}],
        menuType: [{ required: true, message: '菜单类型不能为空', trigger: ['blur', 'change']}],
    },
});

const { queryParams, form, rules } = toRefs(data);
const configData = computed(() => {
    let config = {
        itemConfig: [
            {
                type: "input",
                prop: "menuName",
                label: "菜单名称",
                placeholder: "请输入"
            },
            {
                type: "select",
                prop: "status",
                label: "状态",
                placeholder: "请选择",
                optList: statusOptions
            },
            {
                type: "datetimerange",
                prop: "createTime",
                label: "创建时间",
                dateFormate: "YYYY-MM-DD HH:mm:ss",
                placeholder: "请选择"
            },
        ],
        operate: [
            {
                icon: "Search",
                type: "primary",
                name: "查询",
                handleClick: getList,
                rule: false,
            },
            {
                icon: "RefreshRight",
                type: "info",
                name: "重置",
                handleClick: reset,
                rule: false,
            },
            {
                icon: "Plus",
                type: "success",
                name: "新增",
                handleClick: handleAdd,
                rule: true
            },
            {
                icon: "Plus",
                type: "warning",
                name: "展开/折叠",
                handleClick: toggleExpandAll,
                rule: false,
            }
        ],
        rules: {},
    };
    return config;
});
/** 查询菜单列表 */
function getList() {
    loading.value = true;
    menuList(queryParams.value).then(response => {
        dataList.value = proxy!.handleTree(response.data, 'menuId');
        loading.value = false;
    });
}
/** 查询菜单下拉树结构 */
function getTreeselect() {
    menuOptions.value = [];
    menuList().then((response: any) => {
        const menu: any = { menuId: 0, menuName: '主类目', children: [] };
        menu.children = proxy!.handleTree(response.data, 'menuId');
        menuOptions.value.push(menu);
    });
}
function cancel(){
    const menuFormRef = proxy?.$refs['menuRef'] as FormInstance | undefined;
    if (menuFormRef?.resetFields) {
        menuFormRef.resetFields();
    }
    form.value = {
        menuId: null,
        parentId: null,
        menuName: "",
        icon: "",
        path: "",
        component: "Layout",
        menuSort: 0,
        redirect: "",
        status: 1,
        hidden: 1,
        noCache: 2,
        alwaysShow: 2,
        breadcrumb: 1,
        affix: 1,
        menuType: "D",
        isFrame: 2,
        name: "",
        remark: ""
    };
    open.value = false;
}
/** 表单重置 */
function reset() {
    queryParams.value = {
        menuName: undefined,
        status: undefined,
        createTime: undefined
    }
    getList();
}


/** 展示下拉图标 */
function showSelectIcon() {
    iconSelectRef.value.reset();
    showChooseIcon.value = true;
}
/** 选择图标 */
function selected(name: string) {
    form.value.icon = name;
    showChooseIcon.value = false;
}
/** 图标外层点击隐藏下拉列表 */
function hideSelectIcon(event: any) {
    let elem = event.relatedTarget || event.srcElement || event.target || event.currentTarget;
    let className = elem.className;
    if (className !== 'el-input__inner') {
        showChooseIcon.value = false;
    }
}
/** 展开/折叠操作 */
function toggleExpandAll() {
    refreshTable.value = false;
    isExpandAll.value = !isExpandAll.value;
    nextTick(() => {
        refreshTable.value = true;
    });
}
function handleRadio(val: string) {
    if (val == "D") {
        form.value.parentId = null;
        form.value.component = "Layout";
        form.value.alwaysShow = 1;
    } else {
        form.value.component = "";
    }
}

/** 新增按钮操作 */
function handleAdd(row: any) {
    getTreeselect();
    if (row != null && row.menuId) {
        form.value.parentId = row.menuId;
        form.value.menuType = "";
        form.value.component = "";
    } else {
        form.value.parentId = 0;
        form.value.menuType = "D";
    }
    open.value = true;
    title.value = '添加菜单';
}

/** 编辑按钮操作 */
async function handleEdit(row: any) {
    form.value = {...row};
    open.value = true;
    title.value = '编辑菜单';
}
/** 提交按钮 */
function submitForm() {
    (proxy?.$refs['menuRef'] as any).validate((valid: any) => {
        if (valid) {
            if (form.value.menuId !== undefined && form.value.menuId !== null && form.value.menuId !== "") {
                menuEdit(form.value).then((response: any) => {
                    proxy!.$modal.msgSuccess(response.msg);
                    cancel();
                    reset();
                });
            } else {
                menuAdd(form.value).then((response: any) => {
                    proxy!.$modal.msgSuccess(response.msg);
                    cancel();
                    reset();
                });
            }
        }
    });
}
/** 删除按钮操作 */
function handleRemove(row: any) {
    proxy!.$modal
        .confirm('是否确认删除菜单名称为"' + row.menuName + '"的数据项?')
        .then(function () {
            return menuRemove(row.id);
        })
        .then((res: any) => {
            getList();
            proxy!.$modal.msgSuccess(res.msg);
        });
}

getList();
</script>
<style scoped lang="scss">
.el-tree-select {
    width: 100%;
}
</style>